import { NextResponse } from 'next/server'
import { jwtVerify } from 'jose'

const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET || 'your-secret-key')

export async function getUser(request: Request) {
    const authHeader = request.headers.get('Authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }
    
    try {
      const token = authHeader.split(' ')[1]
      const { payload } = await jwtVerify(token, JWT_SECRET)
      return payload.id as string
    } catch (error) {
      return NextResponse.json(
        { error: '无效或过期的token' },
        { status: 401 }
      )
    }
}